 <template>
  <div class="template">
     <div class="search">
      <div class="search-center">
        <div class="search-item">
            <Input clearable
            v-model="search.id"
            placeholder="ID"
            style="width: 150px;"
            ></Input>
        </div>
        <div class="search-item">
            <Input clearable
            v-model="search.title"
            placeholder="名称"
            style="width: 150px;"
            ></Input>
        </div>
        <div class="search-item">
            <Select clearable
                style="width:100px;"
                v-model="search.typeId"
                :label-in-value="true"
                placeholder="分类"
                class="select"
              >
             <Option v-for="(item,index) in apiData.producttypeList" :key="index" :value="item.id+''" :label="item.name">
              <div :class="item.level==2?'pdl10':''"><span v-if="item.level==2">——</span>{{item.name}}</div>
             </Option>
            </Select>
        </div>
        <div class="search-item">
            <Select clearable
                style="width:100px;"
                v-model="search.tag"
                :label-in-value="true"
                placeholder="标签"
                class="select"
              >
             <Option v-for="(item,index) in apiData.productAllTag" :key="index" :value="item" :label="item" v-if="item"></Option>
            </Select>
        </div>
        <div class="search-item">
            <Select clearable
                style="width:100px;"
                v-model="search.status"
                :label-in-value="true"
                placeholder="状态"
                class="select"
              >
             <Option value="0" label="下架"></Option>
             <Option value="1" label="上架"></Option>
             <Option value="-1" label="已删除"></Option>
            </Select>
        </div>

         <Button
          style="width: 80px;margin-right: 10px;margin-bottom:5px"
          type="primary"
          icon="ios-search"
          @click="searchFn"
          >查询</Button>
      </div>    
      <div class="search-center"><Button
          style="width: 80px;"
          type="primary"
          @click="addPRoduct"
          >新增商品</Button></div>
    </div>
    <div class="table">
      <Table
      ref="selection"
      :row-class-name="rowClassName"
        @on-select="selectSupplier"
        @on-select-cancel="selectSupplier"
        @on-select-all="selectSupplier"
        @on-select-all-cancel="selectSupplier"
        :columns="diyData.columns"
        :data="apiData.tableList"
        :draggable="true"
         @on-drag-drop="changeTableSort"
      >
        <template slot="footer">
          <div class="pagination">
            <Button  style="margin-right: 10px;"  @click="handleSelectAll(true)">全选</Button>
            <Button  style="margin-right: 10px;"  @click="batchWarehous(1)">批量上架</Button>
             <Button  style="margin-right: 10px;" @click="batchWarehous(0)">批量下架</Button>
            <Button  style="margin-right: 10px;" @click="getShowModal(1)">批量分类</Button>
            <Button  style="margin-right: 10px;" @click="getShowModal(2)">批量标签</Button>



          </div>
             <Page
            :total="apiData.total"
            show-total
            :page-size="search.pageSize"
            :current="search.pageNo"
            @on-change="pageChange"
            @on-page-size-change="pageSizeChange"
            class-name="footer-page"
            show-elevator
            show-sizer
          ></Page>
        </template>
      </Table>
    </div>

     <Drawer title="" width="400" :closable="false" v-model="diyDom.showModal">
        <div class="Drawer-content" >
               <Form
                  ref="editForm"
                  :model="form"
                  :label-width="100"
                >
                <FormItem label="商品分类：" prop="typeId" v-if="diyDom.type == 1">
                  <!-- <treeselect
                  style="width: 200px"
                      v-model="form.typeId"
                      :options="apiData.producttypeList"
                      placeholder="商品分类"
                    /> -->
                     <Select clearable
                style="width:200px;"
                v-model="form.typeId"
                placeholder="商品分类"
              >
             <Option v-for="(item,index) in apiData.producttypeList" :key="index" :value="item.id+''" :label="item.name">
              <div :class="item.level==2?'pdl10':''"><span v-if="item.level==2">————</span>{{item.name}}</div>


             </Option>
       
            </Select>
                </FormItem>
                <FormItem label="商品标签：" prop="tag" v-if="diyDom.type == 2">
                          <div>
                            <Input
                              placeholder="请输入商品标签，不超过3个字"
                              v-model="form.tag"
                              maxlength="3"
                              style="width:210px"
                            />
                          </div>
                          <div>
                            <span class="tag" @click="form.tag='优选'">优选</span>
                            <span class="tag" @click="form.tag='精品'">精品</span>
                            <span class="tag" @click="form.tag='S级'">S级</span>
                          </div>
                  </FormItem>
                </Form>
             <div>
              <Button style="width: 90px" @click="diyDom.showModal=false">取消</Button>
              <Button type="primary" style="width: 90px; margin-left: 20px" @click="getSure" >确定</Button>
            </div>
        </div>
    </Drawer>
  </div>
</template>

<script>
import {apiProducttypeList} from '@/api/classification-manage.js'
import {apiProductList,apiProductAllTag,apiProductChangeLabel,apiProductChangeSalestatus,apiProductChangeTag,apiProductChangeType,apiProductDelete,apiProductMove,apiProductDrag } from '@/api/product-manage.js'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'product-manage',
  components: { Treeselect},
  data () {
    return {
      search: {
        title:'',
        label:'',
        status:'',
        tag:'',
        title:'',
        typeId:'',
        id:'',
        pageNo: 1,
        pageSize: 10,
      },
      diyDom:{
        showModal:false,
        type:1,//1分类,2,标签,3,标记
      },
      form:{
        typeId:'',
        tag:'',
        hot:'',
        newest:'',
      },
      diyData: {
        ids:'',
        orderNo:'',
        columns: [
           {
              type: 'selection',
              width: 60,
              align: 'center'
          },
          {
            title: 'ID',
            width:'100px',     
            key: 'id',  
          },
          {
            title: '产品编号',
            width:'150px',     
            key: 'code',  
          },
          {
            title: '略缩图',
            width:'150px',
           render: (h, params) => {
              return h('img', {
                    attrs: {
                        src: params.row.img.split(',')[0],
                    },
                    style: {
                        width: '50px',
                    },
                })
             }
          },
           {
            title: '名称',
            width:'200px',
            key: 'title',
          },
          {
            title: '分类',
            width:'180px',
            key: 'typeName',
          },
          {
            title: '标签',
            width:'150px',
            key: 'tag',
          },
          {
            title: '价格',
            width:'150px',
            key: '',
            render: (h, params) => {
              var html=''
              if(params.row.minPrice&&params.row.maxPrice){
                html=[h('p',params.row.minPrice+'-'+params.row.maxPrice)]
              }else if(params.row.minPrice&&!params.row.maxPrice){
                html=[h('p',params.row.minPrice)]
              }else if(!params.row.minPrice&&params.row.maxPrice){
                html=[h('p',params.row.maxPrice)]
              }else{
                 html=[h('p',params.row.price)]
              }
              return h('div', html)
             }
          },
          {
            title: '库存',
            width:100,
            key:'reserve'
          },
          {
            title: '销量(30日)',
            width:'150px',
            key: 'sales',
          },
          {
            title: '状态',
            width:'100px',
            key: 'status',
            render: (h, params) => {
              return h('div', [
                h('p',params.row.status==1?'上架':params.row.status==-1?'已删除':'下架'),
              ])
             }
          },
          {
            title: ' ',
          },
           {
            title: '操作',
            width:'200px',
            fixed: 'right',
            render: (h, params) => {
                  return h('div', [
                      h('Button', {
                          props: {
                            size: 'small',
                          },
                          style:{
                              marginRight:'10px',
                              fontSize:'14px',
                          },
                          on: {
                              click: () => {
                                sessionStorage.setItem('search',JSON.stringify(this.search))
                                  this.$router.push({
                                    name: "add-product",
                                    query: {
                                        id: params.row.id,
                                    },
                                    });
                              }
                          },                            
                        },
                      '编辑'
                      ),
                      h('Button', {
                          props: {
                            size: 'small',
                          },
                          style:{
                              marginRight:'10px',
                              fontSize:'14px',
                              display:params.row.status==1?'none':''
                          },
                          on: {
                              click: () => {
                                 this.$Modal.confirm({
                                    title: '提示',
                                    content: '确认上架当前商品',
                                    onOk: () => {
                                        apiProductChangeSalestatus({
                                            ids:params.row.id,
                                             status:1
                                        }).then(res => {
                                            this.$Message.success('操作成功');
                                            this.getTableList();
                                        });
                                    }
                                });
                              }
                          },                            
                        },
                      '上架'
                      ),
                      h('Button', {
                          props: {
                            size: 'small',
                          },
                          style:{
                              marginRight:'10px',
                              fontSize:'14px',
                              display:params.row.status!=1?'none':''
                          },
                          on: {
                              click: () => {
                                 this.$Modal.confirm({
                                    title: '提示',
                                    content: '确认下架当前商品',
                                    onOk: () => {
                                        apiProductChangeSalestatus({
                                            ids: params.row.id,
                                            status:'0'
                                        }).then(res => {
                                            this.$Message.success('操作成功');
                                            this.getTableList();
                                        });
                                    }
                                });
                              }
                          },                            
                        },
                      '下架'
                      ),
                //        h(
                //   'Button',
                //   {
                //     style: {
                //       marginRight: '10px',
                //       color: '#383838',
                //     },
                //     on: {
                //       click: () => {
                //         var opt={
                //               id1:this.apiData.tableList[params.index-1>0?params.index-1:0].id,
                //               id2:params.row.id,
                //             }
                //             this.getProductProductMove(opt)
                //       }
                //     }
                //   },
                //   '上移'
                // ),
                // h(
                //   'Button',
                //   {
                //     style: {
                //       marginRight: '10px',
                //       color: '#383838',
                //     },
                //     on: {
                //       click: () => {
                //         console.log(params.index+1,this.search.pageSize,params.index+1> Number(this.search.pageSize),params.index+1>this.search.pageSize?params.index:params.index+1)
                //          var opt={
                //               id2:this.apiData.tableList[params.index+1>=Number(this.search.pageSize) ?params.index:params.index+1].id,
                //               id1:params.row.id,
                //             }
                //             this.getProductProductMove(opt)
                //       }
                //     }
                //   },
                //   '下移'
                // ),
                      h('Button', {
                          props: {
                            size: 'small',
                          },
                          style:{
                              marginRight:'10px',
                              fontSize:'14px',
                          },
                          on: {
                              click: () => {
                                this.$Modal.confirm({
                                    title: '提示',
                                    content: '确认删除？',
                                    onOk: () => {
                                        apiProductDelete({
                                            ids: params.row.id
                                        }).then(res => {
                                            this.$Message.success('操作成功');
                                            this.getTableList();
                                        });
                                    }
                                });
                              }
                          },                            
                        },
                      '删除'
                      ),
                  ])
                }
          },
        ]
      },
      apiData: {
        total: 0,
        infor:null,
        tableList: [], 
        productAllTag:[],
        producttypeList:[],
      }
    }      
  },
  methods: {
    rowClassName (row, index) {
        if (row.status != 1) {
            return 'demo-table-info-column';
        }
        return '';
    },
    //商品分类
    getProducttypeList(){
        apiProducttypeList().then(res => {
            // var obj=[]
            // for(var i=0;i<res.data.length;i++){
            //     if(res.data[i].level==1){
            //         var data=res.data[i]
            //         data.children=[]
            //         data.label=res.data[i].name
            //         data.isEdit=false
            //         obj.push(data)
            //     }else{
            //         obj=obj.map(item=>{
            //             if(item.id==res.data[i].parentId){
            //                 var children=res.data[i]
            //                 children.isEdit=false
            //                 children.label=res.data[i].name
            //                 item.children.push(children)
            //             }
            //             return item
            //         })
            //     }
               
            // }
            // this.apiData.producttypeList=obj.map(item=>{
            //   if(item.children.length==0){
            //     delete item.children
            //   }
            //  return item
            // })
             this.apiData.producttypeList=res.data
        });
    },
    selectSupplier(e){
      var ids=e.map(res=>{
          return res.id
      })
      this.diyData.ids=ids.join(',')
      console.log(this.diyData.ids)
    },
    handleSelectAll (status) {
        this.$refs.selection.selectAll(status);
    },
    //所有标签
    getProductAllTag(){
      apiProductAllTag().then(res => {
        this.apiData.productAllTag=res.data
      });
    },
        // 分页
    pageChange (e) {
      this.search.pageNo = e
      this.getTableList()
    },
    pageSizeChange (e) {
      this.search.pageSize = e
      this.search.pageNo = 1
      this.getTableList()
    },
    // 搜索
    searchFn () {
      this.search.pageNo = 1
      this.getTableList()
    }, 
    addPRoduct(){
      this.$router.push({
        name: "add-product",
      });
    },
    getTableList(){
      this.$store.commit('setSpinShow', true)
      var opt = { ...this.search }
      apiProductList(opt).then((res) => {
        const {
          list,
          totalCount
        } = res.data
        
        this.apiData.tableList = list
        this.apiData.total = totalCount
      }).finally(() => this.$store.commit('setSpinShow', false))
    },
    batchWarehous(i){
      var that=this
      if(this.diyData.ids){
        this.$Modal.confirm({
          title: '提示', 
          content:`是否确认批量${i==1?'上架':'下架'}当前产品?`,
          onOk: () => {   
            var opt={
              ids:this.diyData.ids,
              status:i
            }  
            apiProductChangeSalestatus(opt).then(res=>{
              that.getTableList();
            })                 
          }
        })
      }else{
        this.$Modal.error({
          title: '系统提示',
          content: '请先选择产品'
        })
      }
       
    },

    //标签
    getShowModal(i){
        var that=this
        this.diyDom.type=i
        this.form.typeId=''
        if(this.diyData.ids){
          this.diyDom.showModal=true
        }else{
        this.$Modal.error({
          title: '系统提示',
          content: '请先选择产品'
        })
      }
    },
    getSure(){
      if(this.diyDom.type==1){
        var opt={
          ids:this.diyData.ids,
          typeId:this.form.typeId,
        }
        apiProductChangeType(opt).then(res=>{
          this.$Message.success('保存成功')
          this.diyDom.showModal=false
          this.getTableList();
        })
      }else if(this.diyDom.type==2){
        var opt={
          ids:this.diyData.ids,
          tag:this.form.tag,
        }
         apiProductChangeTag(opt).then(res=>{
           this.$Message.success('保存成功')
           this.diyDom.showModal=false
            this.getTableList();
        })
      }
    },
     getProductProductMove(opt){
      apiProductMove(opt).then(res=>{
        this.getTableList();
      })
    },
     changeTableSort(oldIndex,newIndex){
      console.log(oldIndex,newIndex)
      var tableList=this.apiData.tableList
      var  list=[]
      if(oldIndex<newIndex){
        for(var i=oldIndex;i<=newIndex;i++){
          if(i==oldIndex){
            var obj={
              id:tableList[i].id,
              sort:Number(tableList[newIndex].sort)
            }
            list.push(obj)
          }else{
              var obj={
                id:tableList[i].id,
                sort:Number(tableList[i].sort)-1
              }
              list.push(obj)
          }
        }
      }else if(oldIndex>newIndex){
         var obj={
              id:tableList[oldIndex].id,
              sort:Number(tableList[newIndex].sort)
            }
            list.push(obj)
        for(var i=newIndex;i<oldIndex;i++){
          if(i!=oldIndex){
             var obj={
                id:tableList[i].id,
                sort:Number(tableList[i].sort)+1
              }
              list.push(obj)
           
          }
        }
      }
      apiProductDrag({list:list}).then(res=>{
         this.getTableList()
      })
    },

  },
   mounted () {
    var search=sessionStorage.getItem('search')||''
    if(search){
      this.search=JSON.parse(search)
      sessionStorage.removeItem('search')
    }
    this.getTableList()
    this.getProductAllTag()
    this.getProducttypeList()
  },
}
</script>

<style scoped lang="less">
.template{
  width: 100%;
  background: #fff;
  padding: 20px;
  box-sizing: border-box;
}
.button-border{
  margin-right: 10px;
  
}
.tag{
  width: 50px;
height: 26px;
opacity: 1;
border-radius: 5px;
background: rgba(255, 87, 51, 1);
text-align: center;
line-height: 26px;
font-size: 14px;
font-weight: 400;
color: rgba(255, 255, 255, 1);
margin-left: 10px;
display: inline-block;
}
</style>
 <style>
.ivu-table .demo-table-info-column td{
        color: rgb(193, 193, 193) !important;
    }
 </style>